﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using WindowsPhoneRssReader.Models;
using WindowsPhoneRssReader.Utils;

namespace WindowsPhoneRssReader
{
    public partial class AddRssPage : PhoneApplicationPage
    {
        private Subscription model;
        public AddRssPage()
        {
            InitializeComponent();

            model = new Subscription();
            DataContext = model;
            model.PropertyChanged += (s, e1) => EnableProgressBar(false);

        }

        private void _buttonTest_Click(object sender, RoutedEventArgs e)
        {
            EnableProgressBar(true);

            var url = _textboxAddress.Text;
            var subscription = (DataContext as Subscription);
            if (subscription == null) return;

            subscription.CheckRss(url);
        }

        private void EnableProgressBar(bool enable)
        {
            progressbar.Visibility = enable ? Visibility.Visible : Visibility.Collapsed;
            progressbar.IsIndeterminate = enable;
        }

        private void _buttonAdd_Click(object sender, RoutedEventArgs e)
        {
            var subscription = (DataContext as Subscription);
            if (subscription == null) return;
            var feed = new Feed
                           {
                               Id = XmlAction.NextId(),
                               FeedName = subscription.Title,
                               FeedUrl = _textboxAddress.Text,
                               ParentModel = App.RssReader
                           };
            var success = XmlAction.SaveFeedsData(feed);
            if (success)
            {
                MessageBox.Show("Add " + feed.FeedName + " OK");
                App.RssReader.Feeds.Add(feed);
                Deployment.Current.Dispatcher.BeginInvoke(feed.LoadFeed);
            }
            else
            {
                MessageBox.Show("Failure");

            }
            if (model == null) return;
            model.Success = false;
        }

        private void _textboxAddress_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (model == null) return;
            model.Success = false;
        }
    }
}